package com.aispeech.task.config;

import com.aispeech.http.RestfulClient;
import com.aispeech.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class EtcdConfig {
    private static EtcdConfig ins = new EtcdConfig();

    private String etcdURL;
    private String etcdPath;
    private Map<Object, Object> data;

    private EtcdConfig() {
        data = new ConcurrentHashMap<>();

        readEnvVariables();

        if (StringUtils.isNullOrEmpty(etcdURL) || StringUtils.isNullOrEmpty(etcdPath)) {
            fromPropertiesFile();
        } else {
            fromEtcdServer();
        }
    }

    public static EtcdConfig Instance() {
        return ins;
    }

    public Map<Object, Object> current() {
        return data;
    }

    private void readEnvVariables() {
        Map map = System.getenv();

        for (Object o : map.entrySet()) {
            Map.Entry entry = (Map.Entry) o;
            String key = entry.getKey().toString();

            if (key.equals("ETCD_SERVER_ADDR_INTERNAL")) {
                etcdURL = entry.getValue().toString();
            } else if (key.equals("ETCD_PROJECT_IDENTIFICATION")) {
                etcdPath = entry.getValue().toString();
            }
        }
    }

    private void fromPropertiesFile() {
        String path = System.getProperty("config.dir");

        File file = StringUtils.isNullOrEmpty(path)
                ? new File(getClass().getResource("/app.properties").getFile())
                : new File(path + "/app.properties");

        try {
            FileInputStream fis = new FileInputStream(file);
            Properties props = new Properties();
            props.load(fis);

            data = props;

            fis.close();
        } catch (IOException e) {
            log.warn("Not found config from path: " + path);
//            System.exit(101);
        }
    }

    private void fromEtcdServer() {
        JSONObject conf = RestfulClient.getAsJSONObject(String.format("%s/v2/keys/%s", etcdURL, etcdPath));
        data = conf.toJavaObject(data.getClass());
    }
}
